#ifndef CUSTOMTEXTBROWSER_H
#define CUSTOMTEXTBROWSER_H

#include <QTextBrowser>
#include <QMenu>
#include <QAction>
#include <QClipboard>
#include <QMessageBox>
class CustomTextBrowser : public QTextBrowser {
    Q_OBJECT
public:
    CustomTextBrowser(QWidget* parent = nullptr) : QTextBrowser(parent) {
        // 创建自定义右键菜单
        m_pContextMenu = new QMenu(this);
        m_pCopyAction = new QAction(tr("复制(&C)"), this);
        m_pCopyImageAction = new QAction(tr("复制图片"), this);

        m_pContextMenu->addAction(m_pCopyAction);
        m_pContextMenu->addAction(m_pCopyImageAction);

        // 连接信号与槽
        connect(m_pCopyAction, &QAction::triggered, this, &CustomTextBrowser::copyText);
        connect(m_pCopyImageAction, &QAction::triggered, this, &CustomTextBrowser::copyImage);
    }

protected:
    void contextMenuEvent(QContextMenuEvent* event) override {
        m_pContextMenu->exec(event->globalPos());
    }

private slots:
    void copyText() {
        QTextCursor cursor = textCursor();
        if (!cursor.hasSelection()) {
            QMessageBox::warning(this, tr("警告"), tr("没有选中的文本！"));
            return;
        }
        QClipboard* clipboard = QApplication::clipboard();
        clipboard->setText(cursor.selectedText());
    }

    void copyImage() {
        QTextCursor cursor = textCursor();
        QTextDocument* doc = document();
        QTextImageFormat imageFormat = doc->resource(cursor.position()).value<QTextImageFormat>();
        if (imageFormat.isValid()) {
            QString imageUrl = imageFormat.name();
            if (imageUrl.startsWith("data:image")) {
                QByteArray imageData = imageUrl.mid(imageUrl.indexOf(",") + 1).toUtf8();
                QClipboard* clipboard = QApplication::clipboard();
                clipboard->setPixmap(QPixmap());
                clipboard->setPixmap(QPixmap::fromImage(QImage::fromData(QByteArray::fromBase64(imageData))));
            }
        } else {
            QMessageBox::warning(this, tr("警告"), tr("没有选中的图片！"));
        }
    }

private:
    QMenu* m_pContextMenu;
    QAction* m_pCopyAction;
    QAction* m_pCopyImageAction;
};

#endif // CUSTOMTEXTBROWSER_H
